package com.gome.splunk;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gome.splunk.utils.UpdateUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gome.splunk.DataBase.*;

import android.app.DownloadManager;
import android.content.IntentFilter;
import android.webkit.MimeTypeMap;
import android.app.Service;
import android.os.Build;
import android.content.BroadcastReceiver;

import android.annotation.TargetApi;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import android.os.Handler;
import android.os.Message;
import java.util.TimerTask;


import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.gome.splunk.updatelibrary.utils.UpdateAppManager;
import com.gome.splunk.DataBase.ErrorInfo;
import com.gome.splunk.Common.*;
import com.gome.splunk.ModelClass.UpdateErrorMessageInfo;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import static android.R.attr.delay;
import static android.R.attr.handle;
import static android.R.attr.numbersBackgroundColor;


/***
 * 
 * 
 * @author LiangCaiHong
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class SplunkActivity extends Activity {
    public final static int RESULT_CODE = 1;
    private FrameLayout frameLayout;// 进度条
    public WebView mWebView;
    private LinearLayout empty_img_layout;
    private LinearLayout no_net_layout;
    private String url;
    private ProgressDialog mDialog;
    private Context mContext;
    private long exitTime = 0;


    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;

    private ErrorInfoDAO errorInfoDAO;

    /******************************************** webView 加载 URL**************************************/
   // private final static String mHomePageUrl = "http://10.144.35.67:8080/gomesplunk/";
    //http://10.58.50.229:8080/report/appDate/index.af?userName=%E6%A2%81%E5%BD%A9%E8%99%B9
    // 测试环境
//    private final static String mHomePageUrl = "http://10.58.62.168:8090/gomesplunk/";
    // 正式环境
    private final static String mHomePageUrl = "http://splunkapp.gome.com.cn/gomesplunk/";

    // 新环境
//    private final  static  String mHomePageUrl = "http://splunkapp.atguat.com.cn/";

    /******************************************** 上传错误日志 URL **************************************/
    // 测试环境
    private final static String upDateErrorInfoRUL = "http://splunkapp.atguat.com.cn/api/applog";

    // 正式环境
//    private final static String upDateErrorInfoRUL = "http://bigdataapp.gomeplus.com/app_log";

    private int status = -1;
    private CookieManager mCookieManager;

    private Timer timer;
    private Handler mHandler;

    private class UpdateDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            BDebug.i("tag", "url=" + url);
            BDebug.i("tag", "userAgent=" + userAgent);
            BDebug.i("tag", "contentDisposition=" + contentDisposition);
            BDebug.i("tag", "mimetype=" + mimetype);
            BDebug.i("tag", "contentLength=" + contentLength);
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast t = Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                return;
            }
            DownloaderTask task = new DownloaderTask();
            task.execute(url);
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        errorInfoDAO = new ErrorInfoDAO(this);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        BDebug.i("url", "onCreate");
        mContext = this;

        // 获取权限
        getPersimmions();
        InitWebView();

        // 加载 webView 超时后更新主界面
        mHandler = new Handler(){
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        setTitle("hear me?");
                        //设置主界面
                        mWebView.setVisibility(View.GONE);
                        frameLayout.setVisibility(View.GONE);
                        empty_img_layout.setVisibility(View.VISIBLE);

                        AlertDialog alertDialog = new AlertDialog.Builder(SplunkActivity.this).create();
                        alertDialog.setTitle("提示");
                        alertDialog.setMessage("加载失败，请检查当前网络环境！");
                    alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "重试", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 重新加载 web View
                                frameLayout.setVisibility(View.VISIBLE);
                                empty_img_layout.setVisibility(View.GONE);
                                no_net_layout.setVisibility(View.GONE);
                                loadPage();
                            }
                        });
                        alertDialog.show();
                        break;
                }
                super.handleMessage(msg);
            }

        };

    }

 /********************************** 权限操作 ********************************/
    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();

            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读写权限
            if (addPermission(permissions, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.READ_EXTERNAL_STORAGE Deny \n";
            }

            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    /***
     * 初始化 webview
     */
    public void InitWebView() {
        // mBundle = new Bundle();
        frameLayout = (FrameLayout) findViewById(R.id.ll_webview);
        empty_img_layout = (LinearLayout) findViewById(R.id.empty_image);
        no_net_layout = (LinearLayout) findViewById(R.id.no_net_image);
        ImageView noNetIageView = (ImageView) findViewById(R.id.no_net_img);
        mWebView = (WebView) findViewById(R.id.mywebview);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setSaveFormData(false);
        mWebView.requestFocus();

        WebSettings settings = mWebView.getSettings();
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);

        mCookieManager = CookieManager.getInstance();
        if (isNetworkAvailable(this)) {
            checkUpdate();
            loadPage();
            // wifi 环境下上传错误日志
//            if (DeviceHelper.isWifi(mContext)) {
                updateErrorMessage();
//            }
        } else {
            mWebView.setVisibility(View.GONE);
            frameLayout.setVisibility(View.GONE);
            empty_img_layout.setVisibility(View.GONE);
            no_net_layout.setVisibility(View.VISIBLE);
        }
        mWebView.setWebViewClient(client);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                super.onJsConfirm(view, url, message, result);
                return confirmEixt(result, message);
            }
        });
        // mWebView.setDownloadListener(new UpdateDownLoadListener());
        noNetIageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 1);
            }
        });
    }

    private void checkUpdate() {
        UpdateTask task = new UpdateTask();
        task.execute(mHomePageUrl + "checkUpdate");
    }

    // 内部类
    private class DownloaderTask extends AsyncTask<String, Void, String> {
        public DownloaderTask() {
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String url = params[0];
            try {
                // Log.i("tag", "url="+url);
                String fileName = "Splunk.apk";
                fileName = URLDecoder.decode(fileName);
                BDebug.i("tag", "fileName=" + fileName);
                File directory = Environment.getExternalStorageDirectory();
                File file = new File(directory, fileName);
                HttpClient client = new DefaultHttpClient();
                // client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
                HttpGet get = new HttpGet(url);
                HttpResponse response = client.execute(get);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream input = entity.getContent();
                    writeToSDCard(fileName, input);
                    input.close();
                    // entity.consumeContent();
                    return fileName;
                } else {
                    return null;
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }

        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub  后台操作完成后调用
            super.onPostExecute(result);
            closeProgressDialog();
            if (result == null) {
                Toast t = Toast.makeText(mContext, "", Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                return;
            } else if (result.equals("noupdate")) {

            } else {
                File directory = Environment.getExternalStorageDirectory();
                File file = new File(directory, result);
                BDebug.i("tag", "Path=" + file.getAbsolutePath());
                Intent intent = getFileIntent(file);
                startActivity(intent);
            }

        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            showProgressDialog();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }

    }

    // 内部类
    private class UpdateTask extends AsyncTask<String, Void, UpdateInfo> {
        public UpdateTask() {
        }

        @Override
        protected UpdateInfo doInBackground(String... params) {
            // TODO Auto-generated method stub
            String urlStr = params[0];
            try {
                String nowVersion = getVersionName();
                URL url = new URL(urlStr);
                if (BDebug.IsDebug)
                    BDebug.i("update", "update url:" + url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                // 获取到文件的大小
                InputStream is = conn.getInputStream();
                UpdateInfo serverUpdateInfo = UpdateUtil.getUpdataInfo(is);
                if (BDebug.IsDebug) {
                    BDebug.i("update", "nowversion:" + nowVersion);
                    BDebug.i("update", "Serverversion:" + serverUpdateInfo.getVersion());
                    BDebug.i("update", "updateUrl:" + serverUpdateInfo.getUrl());
                }
                return serverUpdateInfo;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }

        }

        @Override
        protected void onPostExecute(final UpdateInfo result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            closeProgressDialog();
            if (result == null) {
                // Toast t = Toast.makeText(mContext, "", Toast.LENGTH_LONG);
                // t.setGravity(Gravity.CENTER, 0, 0);
                // t.show();
                return;
            } else {
                String nowVersion = getVersionName();
                if (nowVersion == null || result == null) {
                    return;
                }
                double nowVersionNum = Double.parseDouble(nowVersion);
                double resultVersionNum = Double.parseDouble(result.getVersion());

                if (nowVersionNum < resultVersionNum) {
                    AlertDialog alertDialog = new AlertDialog.Builder(SplunkActivity.this).create();
                    alertDialog.setTitle("更新提示");
                    alertDialog.setMessage(result.getDescription());
//                    alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    });
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "升级", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            // 下载升级
//                            DownloaderTask task = new DownloaderTask();
//                            task.execute(result.getUrl());
                            UpdateAppManager.downloadApk(SplunkActivity.this,result.getUrl(),"版本升级","国美大时报");

                        }
                    });
                    alertDialog.show();
                }

            }

        }

    }


    private void showProgressDialog() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(mContext);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
            mDialog.setMessage("正在加载 ，请等待...");
            mDialog.setIndeterminate(false);// 设置进度条是否为不明确
            mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    mDialog = null;
                }
            });
            mDialog.show();
        }
    }

    private void closeProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    public Intent getFileIntent(File file) {
        // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = Uri.fromFile(file);
        String type = getMIMEType(file);
        BDebug.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File directory = Environment.getExternalStorageDirectory();
            File file = new File(directory, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[2048];
                int j = 0;
                while ((j = input.read(b)) != -1) {
                    fos.write(b, 0, j);
                }
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            BDebug.i("tag", "NO SDCard.");
        }
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else {
            // /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    /**
     * 确认退出对话框
     * 
     * @param result
     */
    public boolean confirmEixt(final JsResult result, final String message) {
        AlertDialog alertDialog = new AlertDialog.Builder(SplunkActivity.this).create();
        alertDialog.setTitle("提示");
        if (result == null) {
            alertDialog.setMessage("确定退出吗?");
        } else {
            alertDialog.setMessage(message);
        }
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (result != null) {
                    result.cancel();
                }
            }
        });
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (result != null) {//
                    BDebug.i("cookie", "cookie clean one");
                    if (message.equals("您确定要退出系统么?")) {
                        BDebug.i("cookie", "cookie clean");
                        PreferenceUtils.getInstance(getApplicationContext()).setCookies("");
                        mCookieManager.removeAllCookie();
                    }
                    result.confirm();
                } else {
                    finish();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }

            }
        });
        alertDialog.show();
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        BDebug.i("back", "onKeyDown：keyCode:" + keyCode + ",url:" + url);
        if (url != null) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && (mHomePageUrl.equals(url))) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {

                    finish();
                    System.exit(0);
                }
                // confirmEixt(null, "");
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (url.equals(mHomePageUrl + "download"))) {
                // confirmEixt(null, "");
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {

                    finish();
                    System.exit(0);
                }
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (url.equals(mHomePageUrl + "login"))) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {

                    finish();
                    System.exit(0);
                }
                // confirmEixt(null, "");
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (url.equals(mHomePageUrl + "logout"))) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {

                    finish();
                    System.exit(0);
                }
                // confirmEixt(null, "");
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (url.equals(mHomePageUrl + "seclect"))) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {

                    finish();
                    System.exit(0);
                }
                // confirmEixt(null, "");
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
                mWebView.goBack(); // 后退
                return true;
            }
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {

                finish();
                System.exit(0);
            }
            return true;
        }
        return false;
    }

    WebViewClient client = new WebViewClient() {
        private String startUrl;
        private boolean isReload;
        private boolean isReceivedError = false;

        //这个事件就是开始载入页面调用的，通常我们可以在这设定一个loading的页面，告诉用户程序在等待网络响应。
        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次(JS CSS 图片加载都需要调用)
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            startUrl = url;
            isReload = false;

            BDebug.i("url", url);
            SplunkActivity.this.url = url;
            CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(SplunkActivity.this);
            cookieSyncManager.sync();
            CookieSyncManager.getInstance().sync();
            String cookie = mCookieManager.getCookie(url);
            String homecookie = mCookieManager.getCookie(mHomePageUrl);
            BDebug.i("cookie", "page start url：" + url);
            BDebug.i("cookie", "page start homepageurl cookie：" + homecookie);
            BDebug.i("cookie", "page start url cookie：" + cookie);
            PreferenceUtils.getInstance(getApplicationContext()).setCookies(cookie);
        }

        //加载每个资源 都需要调用。比较start的url和load的url  是否一样 来确定该资源加载时间 ，从而确定是否超时  以及后续操作
        @Override
        public void onLoadResource(WebView view, String url) {
            if (startUrl != null && !startUrl.equals(url)) {
                stopTimer();
            }
            if (startUrl != null && startUrl.equals(url)) {
                startTimer();
            }
            super.onLoadResource(view, url);
        }

        //在页面加载结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // 停止计时器
            stopTimer();
            if (isReceivedError) {
                isReceivedError = false;
                return;
            }
            view.getSettings().setBlockNetworkImage(false);
            if (!isReload) {
                if (view.getVisibility() == View.GONE) {
                    view.setVisibility(View.VISIBLE);
                }
            }

            SplunkActivity.this.url = url;
            BDebug.i("cookie", "page finish url  mCookieManager cookie ：" + mCookieManager.getCookie(mHomePageUrl));
            BDebug.i("cookie","page finish url  PreferenceUtils cookie ："
                            + PreferenceUtils.getInstance(getApplicationContext()).getCookies());
            frameLayout.setVisibility(View.GONE);

        }

        // (报告错误信息)
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            isReceivedError = true;

            view.stopLoading();
            stopTimer();
            view.clearView();
            mWebView.setVisibility(View.GONE);
            no_net_layout.setVisibility(View.GONE);
            empty_img_layout.setVisibility(View.VISIBLE);
            Toast.makeText(SplunkActivity.this, description, Toast.LENGTH_LONG).show();

            //创建错误日志对象
            ErrorInfo er = getNewErrorInfo(description, errorCode);
            // 写入数据库等待下次网络正常时上传
            errorInfoDAO.insertDate(er);
        }

        public ErrorInfo getNewErrorInfo(String errMessage, int errorCode){

            String networkType = DeviceHelper.getAPNTypeString(mContext);
            String operators = DeviceHelper.getOperatorsString(mContext);
            String systemVersion = DeviceHelper.getDeviceSystemVersion();
            String systemType = DeviceHelper.getDeviceModel();
            String requestTime = TimeHelper.getCurrentTime();
            String IMEI = DeviceHelper.getIMEI(mContext);
            String userName = "hupengfei";
            ErrorInfo errorInfo = new ErrorInfo(networkType, operators, requestTime, errorCode, errMessage, mHomePageUrl, systemVersion, systemType, "0", IMEI, userName);
            return errorInfo;
        }
        /********************************** 定时器 ***************************************/
        public void startTimer(){
            if (timer != null) {
                timer.cancel();
            }
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    // 关闭定时器，webview停止加载 上传日志
                    stopTimer();
                    isReload =true;
                    ErrorInfo errorInfo = getNewErrorInfo("网络连接超时！", 404);
                    // 写入数据库等待下次网络正常时上传
                    errorInfoDAO.insertDate(errorInfo);

                    // 创建请求超时信息，停止 webView加载
                    Message message = new Message();
                    message.what = 1;
                    mHandler.sendMessage(message);


                }
            }, 5000, 10000);
        }

        // 停止定时器
        public void stopTimer(){
            if(timer != null){
                timer.cancel();
                startUrl = null;
                // 一定设置为null，否则定时器不会被回收
                timer = null;
            }
        }
    };

    private int getRespStatus(String url) {
        int status = -1;
        try {
            HttpHead head = new HttpHead(url);
            HttpClient client = new DefaultHttpClient();
            HttpResponse resp = client.execute(head);
            status = resp.getStatusLine().getStatusCode();
        } catch (IOException e) {

        }
        return status;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (isNetworkAvailable(this.getApplicationContext())) {
                if (mWebView != null) {
                    loadPage();
                }
            }
        }
    }

    protected boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    public void loadPage() {
        mWebView.setVisibility(View.VISIBLE);
        new AsyncTask<String, Integer, Integer>() {

            @Override
            protected Integer doInBackground(String... params) {
                status = getRespStatus(mHomePageUrl);
                return status;
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (status == 404) {
                    mWebView.setVisibility(View.GONE);
                    frameLayout.setVisibility(View.GONE);
                    empty_img_layout.setVisibility(View.VISIBLE);
                    Toast.makeText(SplunkActivity.this, "404无法找到页面", Toast.LENGTH_LONG).show();
                } else {
                    frameLayout.setVisibility(View.VISIBLE);
                    BDebug.i("cookie", "cookie init url:" + mHomePageUrl);
                    BDebug.i("cookie", "cookie init:" + PreferenceUtils.getInstance(getApplicationContext()).getCookies());
                    CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(SplunkActivity.this);
                    cookieSyncManager.sync();
                    mCookieManager.setCookie(mHomePageUrl, PreferenceUtils.getInstance(getApplicationContext()).getCookies());
                    CookieSyncManager.getInstance().sync();
                    mWebView.loadUrl(mHomePageUrl);
                }
            }
        }.execute();
    }

    private String getVersionName() {
        // 获取packagemanager的实例
        PackageInfo packInfo;
        try {
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return packInfo.versionName;
    }


    public String getJSONString(List<ErrorInfo> infoArray) throws JSONException {
        String jsonString = "";
        JSONArray jsonArray = new JSONArray();
        try {
            for (int i = 0; i < infoArray.size(); i++){
                //"id", "networkType","operators","requestTime","responseCode","errorMessage","RUL","isUploading","systemVersion","systemType"
                JSONObject tmpJsonObj = new JSONObject();
                tmpJsonObj.put("networkType", infoArray.get(i).networkType);
                tmpJsonObj.put("operators", infoArray.get(i).operators);
                tmpJsonObj.put("requestTime", infoArray.get(i).requestTime);
                tmpJsonObj.put("responseCode", infoArray.get(i).responseCode);
                tmpJsonObj.put("errorMessage", infoArray.get(i).errorMessage);
                tmpJsonObj.put("RUL", infoArray.get(i).RUL);
                tmpJsonObj.put("systemVersion", infoArray.get(i).systemVersion);
                tmpJsonObj.put("systemType", infoArray.get(i).systemType);
                tmpJsonObj.put("IMEI", infoArray.get(i).IMEI);
                tmpJsonObj.put("userName", infoArray.get(i).userName);
                jsonArray.put(tmpJsonObj);
            }
            jsonString = jsonArray.toString();
        } catch (JSONException e){
            e.printStackTrace();
        }

        return  jsonString;

    }

    /********************************** 上传错误日志操作 *******************************/
    private void updateErrorMessage(){
//        errorInfoDAO = new ErrorInfoDAO(this);
        if(errorInfoDAO.isDataExist()) {
            String jsonString = "";
            if (errorInfoDAO.isDataExist()) {
                // 存在"未上传"的错误日志
                List<ErrorInfo> errorInfoArray = errorInfoDAO.getAllDate();
                // 将数组转化为 json 字符串上传
                try {
                    jsonString = getJSONString(errorInfoArray);

                    System.out.println("jsongString = " + jsonString);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // 发送请求
                UpdateErrorMessages updateErr = new UpdateErrorMessages();
                updateErr.execute(jsonString);

            }
        }
    }

    // 上传
    private class UpdateErrorMessages extends AsyncTask<String, Void, UpdateErrorMessageInfo> {
        @Override
        protected UpdateErrorMessageInfo doInBackground(String... params) {
            String errMessages = params[0];
            try {
                String nowVersion = getVersionName();
                URL url = new URL(upDateErrorInfoRUL);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(30000);
                // 设置请求方式
                conn.setRequestMethod("POST");
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                // 设置容许输出
                conn.setDoOutput(true);
                conn.connect();

                //获取输出流对象，把请求参数发送打服务器接口
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(errMessages.getBytes("utf-8"));
                outputStream.flush();

                // 获取到文件的大小
                InputStream is = conn.getInputStream();
                String respondString = convertStreamToString(is);

                UpdateErrorMessageInfo updateErrorMessageInfo = UpdateUtil.getUpdateErrorMessageInfo(respondString);
                if (BDebug.IsDebug) {
                    BDebug.i("update", "Serverversion:" + updateErrorMessageInfo.getErrorInfo());
                    BDebug.i("update", "updateUrl:" + updateErrorMessageInfo.getResponseCode());
                }
                return updateErrorMessageInfo;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }

        }

        @Override
        protected void onPostExecute(final UpdateErrorMessageInfo result) {
            super.onPostExecute(result);
            if (result != null){
                Integer responseCode = result.getResponseCode();
                if (responseCode == 200){
                    // 更新数据库
                    errorInfoDAO.updateOrder();
                }
            }
        }
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
